package cn.itcast.com.JDBC.test;


import com.mysql.jdbc.Driver;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;

/**
 * Created by 郭浩 on 2020/9/20 19:14
 */
public class jdtest {
    public static void main(String[] args) throws SQLException {
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        //注册驱动，
        try {
            FileInputStream fileInputStream = new FileInputStream(new File("D:\\代码\\代码\\代码\\cn\\itcast\\com\\JDBC\\jdbc.properties"));
            Properties properties = new Properties();
            properties.load(fileInputStream);
            String user = properties.getProperty("user");
            String password = properties.getProperty("password");
            String url = properties.getProperty("url");
            String driverClassName = properties.getProperty("driverClassName");
            //注册一个驱动管理器
            Class.forName(driverClassName);
            connection = DriverManager.getConnection(url, user, password);
            //使用连接创造一个事务
            statement = connection.createStatement();
            //使用sql语句进行查询,获得结果集
            resultSet = statement.executeQuery("select * from mystudent");
            //结果集无法直接显示数据，需要通过循环进行遍历
            //每一次遍历对应数据库查询到的结果的一行，所以需要一一对应查询的列名
            while (resultSet.next()){
                int id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                int age = resultSet.getInt("age");
                String gender = resultSet.getString("gender");
                System.out.println("id:"+id+" name:"+name+" age:"+age+" gender:"+gender);
            }

        } catch (SQLException | FileNotFoundException throwables) {
            throwables.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                if(connection != null) {
                    connection.close();
                }
                if(statement != null){
                    statement.close();
                }
                if(resultSet != null){
                    resultSet.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }
}
